package com.jrmf.redenvelopes.order.common;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

	private static ApplicationContext context;
	
	private ApplicationContextProvider(){}
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}
	
	@SuppressWarnings("unchecked")
	public static<T> T getBean(String name){
		checkAoolicationContext();
		return (T)context.getBean(name);
	}
	
	@SuppressWarnings("unchecked")
	public static<T> T getBean(Class<T> aClass){
		checkAoolicationContext();
		return (T)context.getBeansOfType(aClass);
	}
	
	public static<T> T getBean(String name,Class<T> aClass){
		checkAoolicationContext();
		return context.getBean(name,aClass);
	}
	
	private static void checkAoolicationContext(){
		Assert.notNull(context,"applicationContext未注入！");
	}

}
